package com.share.gateway.config;

import com.nimbusds.jose.jwk.RSAKey;
import com.share.constant.JwtKeyConstant;
import com.share.constant.SecurityConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * 获取jwt 头部 公钥和私钥
 */
@Configuration
public class JwtTokenConfig {
    /**
     * 解密密钥文件
     * @return 返回解密的数据
     */
    @Bean
    RSAKey rsaKey(){
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                new ClassPathResource(JwtKeyConstant.JWT_KEY_STORE_FILE),
                JwtKeyConstant.JWT_KEY_STORE_PASSWORD.toCharArray()
        );
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(JwtKeyConstant.JWT_KEY_NAME,
                JwtKeyConstant.JWT_KEY_STORE_PASSWORD.toCharArray());

        //获取RSA公钥
       RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        //获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //返回
        return new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(SecurityConstant.JWT_JTI).build();
    }

}
